package com.winning.sjzc.sjjgl.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.github.pagehelper.PageInfo;
import com.winning.sjzc.common.utils.ResponseEntity;
import com.winning.sjzc.sjjgl.entity.*;
import com.winning.sjzc.sjjgl.service.DataSetService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dataSet")
public class DataSetController {
    private static final Logger logger = LogManager.getLogger(DataSetController.class);

    @Autowired
    private DataSetService dss;

    //查询
    @RequestMapping(value = "/queryDataSet", method = RequestMethod.POST)
    public @ResponseBody
    String queryDataSet(@RequestParam String yjlbdm, @RequestParam String sjjfldm, @RequestParam String sjjmc,
                        @RequestParam int  limit, @RequestParam int offset ){
        PageInfo<SJJXX> page=new PageInfo<>();
        try{
            page=dss.queryDataSet(yjlbdm,sjjfldm,sjjmc,limit,offset);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "";
        }
        List<SJJXX> list = page.getList();
        JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
        JSONObject result= new JSONObject();
        result.put("total",page.getTotal());
        result.put("rows",array);
        return JSON.toJSONString(result,new PascalNameFilter())
                .replace("Total","total")
                .replace("Rows","rows");
    }

    //数据集树
    @RequestMapping(value = "/querySjjxxTree", method = RequestMethod.POST)
    public @ResponseBody
    String querySjjxxTree(){
        List<SjjflEntity> list=new ArrayList<SjjflEntity>() ;
        try{
            list=dss.querySjjxxTree();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "";
        }
        return JSON.toJSONString(list,new PascalNameFilter());
    }


    //查询版本号和发布日期
    @RequestMapping(value = "/queryByBbhAndFbrq", method = RequestMethod.GET)
    public @ResponseBody
    ResponseEntity queryBBHAndFBRQ(){
        SJJXX sjjxx= dss.queryBBHAndFBRQ();
        return ResponseEntity.ok().put("sjjxx",sjjxx);
    }

    //查询所有的2级数据集分类
    @RequestMapping(value = "/queryAllSjjfl", method = RequestMethod.GET)
    public @ResponseBody
    ResponseEntity queryAllSjjfl(){
        List<SJJXX> list =new ArrayList<SJJXX>();
        try{
             list= dss.queryAllSjjfl();
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok().put("sjjxx",list);
    }

    //保存数据集
    @RequestMapping(value = "/saveDataSet", method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity saveDataSet(HttpServletRequest request, @RequestBody SJJXX sjjxx) {
        int res = -1;
        try{
            res = dss.saveDataSet(sjjxx);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok().put("res",res);
    }

    //修改数据集
    @RequestMapping(value = "/updateDataSet", method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity updateDataSet(HttpServletRequest request, @RequestBody SJJXX sjjxx) {
        int res = -1;
        try{
            res = dss.updateDataSet(sjjxx);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok().put("res",res);
    }

    //编辑回显
    @RequestMapping(value = "/querySjjxxBySjjdmAndBbh", method = RequestMethod.GET)
    public @ResponseBody
    ResponseEntity querySjjxxBySjjdmAndBbh(@RequestParam String sjjdm,
                                           @RequestParam String bbh  ){
        SJJXX sjjxx=new SJJXX();
        try {
             sjjxx= dss.querySjjxxBySjjdmAndBbh(sjjdm,bbh);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok().put("sjjxx",sjjxx);
    }

    //删除
    @RequestMapping(value = "/deleteDataSet", method = RequestMethod.GET)
    public @ResponseBody
    ResponseEntity  deleteDataSet(@RequestParam String sjjdm, @RequestParam String bbh){
        try {
            dss.deleteDataSet(sjjdm,bbh);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok();
    }

    //发布
    @RequestMapping(value = "/publishDataSet", method = RequestMethod.GET)
    public @ResponseBody
    ResponseEntity  publishDataSet(@RequestParam String bbh, @RequestParam String fbrq){
        int res = -1;
        try {
            res =  dss.publishDataSet(bbh,fbrq);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok().put("res",res);
    }

    //根据数据集代码查询数据元目录
    @RequestMapping(value = "/querySjyml", method = RequestMethod.POST)
    public @ResponseBody
    String querySjyml(@RequestParam String sjjdm, @RequestParam String sjydm,
                      @RequestParam int  limit, @RequestParam int offset ){
        PageInfo<SJYML> page=new PageInfo<>();
        try{
            page=dss.querySjyml(sjjdm,sjydm,limit,offset);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "";
        }
        List<SJYML> list = page.getList();
        JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
        JSONObject result= new JSONObject();
        result.put("total",page.getTotal());
        result.put("rows",array);
        return JSON.toJSONString(result,new PascalNameFilter())
                .replace("Total","total")
                .replace("Rows","rows");
    }

    //删除数据元目录
    @RequestMapping(value = "/deleteSjyml", method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity  deleteSjyml(@RequestBody List<SJYML> list){
        System.out.print(list);
        try {
            dss.deleteSjyml(list);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok();
    }

    //修改数据元目录
    @RequestMapping(value = "/updateSjyml", method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity updateSjyml(HttpServletRequest request, @RequestBody SJYML sjyml) {
        try{
             dss.updateSjyml(sjyml);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok();
    }

    //保存数据元目录
    @RequestMapping(value = "/saveSjyml", method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity saveSjyml(@RequestBody List<SJYML> list) {
        try{
             dss.saveSjyml(list);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResponseEntity.error();
        }
        return ResponseEntity.ok();
    }

    //查询数据集未添加的数据元
    @RequestMapping(value = "/querySjyxxBySjjdm", method = RequestMethod.POST)
    public @ResponseBody
    String querySjyxxBySjjdm(Integer limit, Integer offset, String sjymc, String sjjdm){
        PageInfo<SjyxxEntity> page=new PageInfo<SjyxxEntity>();
        try{
            page=dss.querySjyxxBySjjdm(offset,limit,sjymc,sjjdm);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "";
        }
        List<SjyxxEntity> list = page.getList();
        JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
        JSONObject result= new JSONObject();
        result.put("total",page.getTotal());
        result.put("rows",array);
        return JSON.toJSONString(result,new PascalNameFilter())
                .replace("Total","total")
                .replace("Rows","rows");
    }

    @GetMapping("/exportWord")
    public void exportWord(@RequestParam Map queryMap, HttpServletResponse res) throws Exception {

        File file = new File("数据集信息.docx");
        OutputStream out = new FileOutputStream(file);

        XWPFDocument document = createWord("数据集信息");

        String sjjdms = (String) queryMap.get("sjjdms");
        String[] sjjdmsArr = sjjdms.split(",");
        for (String sjjdm : sjjdmsArr) {
            //插入空行
            XWPFParagraph nullParagraph = document.createParagraph();
            XWPFRun paragraphRun = nullParagraph.createRun();
            paragraphRun.addBreak(BreakType.TEXT_WRAPPING);

            XWPFParagraph sjjdmParagraph = document.createParagraph();
            sjjdmParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun sjjdmParagraphRun = sjjdmParagraph.createRun();
            sjjdmParagraphRun.setText("[" + sjjdm + "]");

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("sjjdm", sjjdm);
            List<SJYML> sjymls = dss.querySjymlBySjjdms(paramMap);
            XWPFTable table = document.createTable(sjymls.size() + 1, SjjExportWordRowHeadEnum.values().length);
            createRowHead(table);
            for (int i = 0; i < sjymls.size(); i++) {
                XWPFTableRow row = table.getRow(i + 1);
                SJYML sjyml = sjymls.get(i);
                int j = 0;
                for (SjjExportWordRowHeadEnum cellEnum : SjjExportWordRowHeadEnum.values()) {
                    XWPFTableCell cell = row.getCell(cellEnum.getCellIndex());
                    CTTcPr cellPr = cell.getCTTc().addNewTcPr();
                    CTTblWidth cellWidth = cellPr.addNewTcW();
                    cellWidth.setW(cellEnum.getCellWidth());
                    XWPFParagraph cellParagraph = cell.addParagraph();
                    cellParagraph.setAlignment(ParagraphAlignment.CENTER);
                    cellParagraph.setVerticalAlignment(TextAlignment.CENTER);
                    XWPFRun cellParagraphRun = cellParagraph.createRun();
                    Field field = sjyml.getClass().getDeclaredField(cellEnum.getColumnName());
                    field.setAccessible(true);
                    cellParagraphRun.setText(String.valueOf(field.get(sjyml)));
                    cellParagraphRun.setFontSize(8);
                    j++;
                }
            }
        }

        document.write(out);
        exportWord(file, res);

    }

    private XWPFDocument createWord(String title) {
        XWPFDocument document = new XWPFDocument();
        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();

        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText(title);
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setBold(true);
        titleParagraphRun.setFontSize(20);

        return document;
    }

    private void createRowHead(XWPFTable table) {
        XWPFTableRow row = table.getRow(0);
        for (SjjExportWordRowHeadEnum cellEnum : SjjExportWordRowHeadEnum.values()) {
            XWPFTableCell cell = row.getCell(cellEnum.getCellIndex());
            CTTcPr cellPr = cell.getCTTc().addNewTcPr();
            CTTblWidth cellWidth = cellPr.addNewTcW();
            cellWidth.setW(cellEnum.getCellWidth());
            XWPFParagraph cellParagraph = cell.addParagraph();
            cellParagraph.setAlignment(ParagraphAlignment.CENTER);
            cellParagraph.setVerticalAlignment(TextAlignment.CENTER);
            XWPFRun cellParagraphRun = cellParagraph.createRun();
            cellParagraphRun.setText(cellEnum.getCellName());
            cellParagraphRun.setFontSize(10);
            cellParagraphRun.setBold(true);
        }
    }


    private void exportWord(File file, HttpServletResponse res) throws UnsupportedEncodingException {
        FileInputStream is = null;
        OutputStream out = null;

        try {
            res.setContentType("APPLIATION/DOWNLOAD");
            res.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            res.setContentLength(-1);

            is = new FileInputStream(file);
            out = res.getOutputStream();
            int readBytes = 0;
            byte[] buffer = new byte[8192];
            while ((readBytes = is.read(buffer, 0, 8192)) != -1) {
                out.write(buffer, 0, readBytes);
            }
            res.flushBuffer();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}
